package com.changgou.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

//自定义Feign拦截器,谁调用,
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //传递令牌
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//获取请求当中的所有参数信息
        //如果参数非空,则进行遍历
        if(requestAttributes!=null){
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

            //如果请求头非空
            if(request!=null){
                //获取所有请求头
                Enumeration<String> headerNames = request.getHeaderNames();
                //死循环遍历请求头信息
                while (headerNames.hasMoreElements()){ //类似于迭代器 iter   hasnext     next()
                    String headerName = headerNames.nextElement();
                    if("authorization".equals(headerName)){
                        String headerValue = request.getHeader(headerName);//获取 authorization 当中 bearer  jwt 令牌信息
                        //传递令牌 ----->将请求头authorization继续往下传递
                        requestTemplate.header(headerName,headerValue);
                    }
                }
            }
        }
    }
}
